﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Linq.Expressions;
using System.Data;
using System.Data.SqlClient;

namespace Warehouse.DataAccess
{
    public partial class WarehouseClassesDataContext
    {
        static TextWriter sLog = new LogWriter();
        partial void OnCreated()
        {
            this.Log = sLog;
        }

        public static string ConnectionString
        {
            get
            {
                return global::Warehouse.DataAccess.Properties.Settings.Default.WarehouseConnectionString;
            }
        }

        public static DataTable GetDataTable(string selectCommandString, List<SqlParameter> parameters)
        {
            SqlCommand cmd = new SqlCommand(selectCommandString);
            if (parameters != null)
            {
                cmd.Parameters.AddRange(parameters.ToArray());
            }
            return GetDataTable(cmd);
        }

        public static DataTable GetDataTable(SqlCommand selectCommand)
        {
            using (WarehouseClassesDataContext datacontext = new WarehouseClassesDataContext())
            {
                selectCommand.Connection = datacontext.Connection as SqlConnection;
                selectCommand.Connection.Open();
                using (datacontext.Connection)
                {
                    SqlDataAdapter sda = new SqlDataAdapter(selectCommand);
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }

    class LogWriter : TextWriter
    {
        public override Encoding Encoding
        {
            get { return Encoding.Default; }
        }
        public override void Write(char value)
        {
            OnWrite(value.ToString());
        }

        public override void Write(string value)
        {
            OnWrite(value);
        }

        public override void Write(char[] buffer, int index, int count)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (index < 0)
            {
                throw new ArgumentOutOfRangeException("index");
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count");
            }
            if ((buffer.Length - index) < count)
            {
                throw new ArgumentException("Invalid Offset Length");
            }
            OnWrite(new string(buffer, index, count));
        }

        void OnWrite(string msg)
        {
            Debug.WriteLine(msg);
        }
    }
}
